package com.example.sunmiv1.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.text.Editable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.example.sunmiv1.R;
import com.example.sunmiv1.adapter.GoodsPriceAdapter;
import com.example.sunmiv1.adapter.PriceQueryAdapter;
import com.example.sunmiv1.adapter.PriceSkuClassAdapter;
import com.example.sunmiv1.entity.ClassifyInfo;
import com.example.sunmiv1.entity.GoodsPriceInfo;
import com.example.sunmiv1.entity.PriceQueryBean;
import com.example.sunmiv1.utils.net.ACache;
import com.example.sunmiv1.utils.net.Common;
import com.example.sunmiv1.utils.net.GsonUtils;
import com.example.sunmiv1.utils.net.HttpUtils;
import com.example.sunmiv1.utils.net.LoadingDialog;
import com.example.sunmiv1.utils.net.TextCallBack;
import com.example.sunmiv1.utils.zxing.Constant;
import com.example.sunmiv1.utils.zxing.activity.CaptureActivity;
import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class PriceQueryActivity extends Activity {

    @BindView(R.id.title_back)
    ImageView titleBack;
    @BindView(R.id.title_title)
    TextView titleTitle;
    @BindView(R.id.price_query_edit)
    EditText priceQueryEdit;
    @BindView(R.id.price_query_search)
    ImageView priceQuerySearch;
    @BindView(R.id.price_query_code)
    ImageView priceQueryCode;
    @BindView(R.id.spinner1)
    Spinner spinner1;
    @BindView(R.id.spinner2)
    Spinner spinner2;
    @BindView(R.id.spinner3)
    Spinner spinner3;
    @BindView(R.id.price_query_list)
    PullToRefreshListView priceQueryList;
    @BindView(R.id.price_query_popup_name)
    TextView priceQueryPopupName;
    @BindView(R.id.price_query_popup_freightNumber)
    TextView priceQueryPopupFreightNumber;
    @BindView(R.id.price_query_popup_inventory)
    EditText priceQueryPopupInventory;
    @BindView(R.id.price_query_popup_stock)
    TextView priceQueryPopupStock;
    @BindView(R.id.price_query_popup_cancel)
    TextView priceQueryPopupCancel;
    @BindView(R.id.price_query_popup_sure)
    TextView priceQueryPopupSure;
    @BindView(R.id.price_query_popup_linear)
    LinearLayout priceQueryPopupLinear;
    @BindView(R.id.price_query_popup_skuPrice)
    TextView priceQueryPopupSkuPrice;
    @BindView(R.id.price_query_popup_skuList)
    ListView priceQueryPopupSkuList;
    @BindView(R.id.priceQuery_name)
    TextView priceQueryName;
    @BindView(R.id.sku_name)
    TextView skuName;
    @BindView(R.id.linear_sku)
    LinearLayout linearSku;
    @BindView(R.id.priceQuery_freightNumber)
    TextView priceQueryFreightNumber;
    @BindView(R.id.priceQuery_code)
    TextView tvPriceQueryCode;
    @BindView(R.id.priceQuery_storeRetail)
    EditText priceQueryStoreRetail;
    @BindView(R.id.priceQuery_storeMember)
    EditText priceQueryStoreMember;
    @BindView(R.id.linear_storeMember)
    LinearLayout linearStoreMember;
    @BindView(R.id.priceQuery_mall)
    EditText priceQueryMall;
    @BindView(R.id.linear_mall)
    LinearLayout linearMall;
    @BindView(R.id.priceQuery_mallMember)
    EditText priceQueryMallMember;
    @BindView(R.id.linear_mallMember)
    LinearLayout linearMallMember;
    @BindView(R.id.priceQuery_plus)
    EditText priceQueryPlus;
    @BindView(R.id.linear_plus)
    LinearLayout linearPlus;
    @BindView(R.id.change_price_cancel)
    TextView changePriceCancel;
    @BindView(R.id.change_price_sure)
    TextView changePriceSure;
    @BindView(R.id.linear_change_price)
    LinearLayout linearChangePrice;
    @BindView(R.id.btn_to_top)
    ImageView btnToTop;

    private ClassifyInfo classifyInfo;
    /**
     * 分類實體類
     */
    private Context context;
    private Intent intent;
    private ACache aCache;
    private static final String TAG = "AddGoodsFragment";
    private int oneIndex, twoIndex, threeIndex;
    private List<ClassifyInfo.GoodscateBean> allList = new ArrayList<>(); //全部數據
    private List<ClassifyInfo.GoodscateBean.ChildBeanX> allTwoList = new ArrayList<>(); //全部數據（二級）
    private List<ClassifyInfo.GoodscateBean.ChildBeanX.ChildBean> allThreeList = new ArrayList<>(); //全部數據（三級）
    private List<PriceQueryBean.GoodslistBean> goodsList = new ArrayList<>();//商品的數據
    private PriceQueryBean priceQueryBean;//商品實體類
    private List<String> childOneList = new ArrayList<>(); //一級分類
    private List<String> childTwoList = new ArrayList<>(); //二級分類
    private List<String> childThreeList = new ArrayList<>(); //三級分類
    private int page = 1; //第幾頁
    private int page_limit = 10; //一頁有多少數據
    private PriceQueryAdapter priceQueryAdapter;//商品的適配器
    private int goodIndex = 0;//點擊的第幾個商品
    private String sku_id = "0";
    private LoadingDialog loadingDialog;
    private HashMap<Integer, String> skuMap;//存放規格
    private List<PriceQueryBean.GoodslistBean.SkuinfoBean> skuInfoBeanList = new ArrayList<>();
    private List<PriceQueryBean.GoodslistBean.SkujsonBean> skuJsonBeanList = new ArrayList<>();
    private GoodsPriceAdapter goodsPriceAdapter;
    private List<GoodsPriceInfo.GoodsListBean> goodsListBeanList = new ArrayList<>();
    private GoodsPriceInfo goodsPriceInfo;
    private DecimalFormat df = new DecimalFormat("0.00");

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_price_query);
        ButterKnife.bind(this);
        context = this;
        aCache = ACache.get(context);
        titleTitle.setText(R.string.priceQueryTitle);
        loadingDialog = new LoadingDialog(context);
        initData();
    }

    private void initData() {
        getClassify();
        refresh();
        setClassifyListener();
    }

    private void refresh() {
        priceQueryList.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                page = 1;
                goodsListBeanList.clear();
                setGoodsPriceAdapter();
                searchGoodsV1();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                searchGoodsV1();
            }
        });
    }

    private void setPriceQueryAdapter() {
        if (priceQueryAdapter == null) {
            priceQueryAdapter = new PriceQueryAdapter(context, goodsList);
            priceQueryList.setAdapter(priceQueryAdapter);
        } else {
            priceQueryAdapter.notifyDataSetChanged();
        }
        priceQueryAdapter.Click(new PriceQueryAdapter.OnListener() {
            @Override
            public void Listener(int index) {
                goodIndex = index;
                Resources resources = context.getResources();

                priceQueryPopupName.setText(resources.getString(R.string.priceQuery_goodName) + goodsList.get(goodIndex).getGoods_name());
                priceQueryPopupFreightNumber.setText(resources.getString(R.string.priceQuery_freightNumber) + goodsList.get(goodIndex).getGoods_number());
                priceQueryPopupStock.setText(resources.getString(R.string.priceQuery_goodPrice) + goodsList.get(goodIndex).getRetail_price());
                if ("2".equals(goodsList.get(index).getAttribute_state()) && goodsList.get(index).getSkujson().size() > 0) {
                    priceQueryPopupSkuPrice.setVisibility(View.VISIBLE);
                    priceQueryPopupSkuList.setVisibility(View.VISIBLE);
                    priceQueryPopupSkuPrice.setText(context.getResources().getString(R.string.priceQuery_skuPrice));
                    skuMap = new HashMap<>();
                    priceQueryPopupSkuPrice.setText("");
                    int infoSize = goodsList.get(goodIndex).getSkuinfo().size();
                    int jsonSize = goodsList.get(goodIndex).getSkujson().size();
                    skuInfoBeanList.clear();
                    skuJsonBeanList.clear();
                    for (int i = 0; i < infoSize; i++) {
                        skuInfoBeanList.add(goodsList.get(goodIndex).getSkuinfo().get(i));
                    }
                    for (int i = 0; i < jsonSize; i++) {
                        skuJsonBeanList.add(goodsList.get(goodIndex).getSkujson().get(i));
                    }
                    PriceSkuClassAdapter priceSkuClassAdapter = new PriceSkuClassAdapter(context, skuInfoBeanList);
                    priceQueryPopupSkuList.setAdapter(priceSkuClassAdapter);
                    priceSkuClassAdapter.notifyDataSetChanged();
                    priceSkuClassAdapter.Sku(new PriceSkuClassAdapter.SkuBean() {
                        @Override
                        public void success(int index, int position, String path) {
                            skuMap.put(index, path);
                            if (skuMap.size() == skuInfoBeanList.size()) {
                                String paths = "";
                                for (int i = skuMap.size() - 1; i >= 0; i--) {
                                    paths = skuMap.get(i) + "," + paths;
                                }
                                paths = paths.substring(0, paths.length() - 1);
                                boolean flag = false;
                                for (int i = 0; i < skuJsonBeanList.size(); i++) {
                                    if (paths.equals(skuJsonBeanList.get(i).getSku_res())) {
                                        flag = true;
                                        priceQueryPopupSkuPrice.setText(context.getResources().getString(R.string.priceQuery_skuPrice)
                                                + skuJsonBeanList.get(i).getRetail_price());
                                        sku_id = skuJsonBeanList.get(i).getId();
                                    }
                                }
                                if (!flag) {
                                    sku_id = "0";
                                    priceQueryPopupSkuPrice.setText(context.getResources().getString(R.string.priceQuery_skuPrice));
                                    Toast.makeText(PriceQueryActivity.this, "未找到您選擇的規格", Toast.LENGTH_SHORT).show();
                                }
                            }
                        }
                    });
                } else {
                    priceQueryPopupSkuPrice.setVisibility(View.GONE);
                    priceQueryPopupSkuList.setVisibility(View.GONE);
                }
                priceQueryPopupLinear.setVisibility(View.VISIBLE);
            }
        });
    }

    /*商品價格適配器*/
    private void setGoodsPriceAdapter() {
        if (goodsPriceAdapter == null) {
            goodsPriceAdapter = new GoodsPriceAdapter(context, goodsListBeanList);
            priceQueryList.setAdapter(goodsPriceAdapter);
        } else {
            goodsPriceAdapter.notifyDataSetChanged();
        }
        goodsPriceAdapter.Click(index -> {
            goodIndex = index;
            Resources resources = context.getResources();
            priceQueryName.setText(resources.getString(R.string.priceQuery_goodName) + goodsListBeanList.get(goodIndex).getGoods_name());
            /*規格名稱*/
            if (goodsListBeanList.get(goodIndex).getAttribute_state().equals("1")) {
                sku_id = "0";
                linearSku.setVisibility(View.GONE);
            } else {
                sku_id = goodsListBeanList.get(goodIndex).getSku_id();
                linearSku.setVisibility(View.VISIBLE);
                skuName.setText(resources.getString(R.string.priceQuery_sku_name) + goodsListBeanList.get(goodIndex).getSku_name());
            }
            /*貨號*/
            if (goodsListBeanList.get(goodIndex).getGoods_number() == null || TextUtils.isEmpty(goodsListBeanList.get(goodIndex).getGoods_number())) {
                priceQueryFreightNumber.setText(resources.getString(R.string.priceQuery_freightNumber) + getString(R.string.priceQuery1));
            } else {
                priceQueryFreightNumber.setText(resources.getString(R.string.priceQuery_goodFreightNumber) + goodsListBeanList.get(goodIndex).getGoods_number());
            }
            /*商品條碼*/
            if (goodsListBeanList.get(goodIndex).getGoods_code() == null || TextUtils.isEmpty(goodsListBeanList.get(goodIndex).getGoods_code())) {
                tvPriceQueryCode.setText(resources.getString(R.string.priceQuery_code) + getString(R.string.priceQuery2));
            } else {
                tvPriceQueryCode.setText(resources.getString(R.string.priceQuery_code) + goodsListBeanList.get(goodIndex).getGoods_code());
            }
            /*店內零售價*/
            SpannableString storeRetailPrice = new SpannableString(df.format(goodsListBeanList.get(goodIndex).getRetail_price()));
            priceQueryStoreRetail.setHint(storeRetailPrice);
            /*店內會員價*/
            if (goodsListBeanList.get(goodIndex).getStore_mem_status().equals("1")) {
                linearStoreMember.setVisibility(View.VISIBLE);
                priceQueryStoreMember.setHint(df.format(goodsListBeanList.get(goodIndex).getStore_mem_price()));
            } else {
                linearStoreMember.setVisibility(View.GONE);
            }
            /*商城價*/
            if (goodsListBeanList.get(goodIndex).getOnline_state().equals("1")) {
                linearMall.setVisibility(View.VISIBLE);
                priceQueryMall.setHint(df.format(goodsListBeanList.get(goodIndex).getOnline_price()));
            } else {
                linearMall.setVisibility(View.GONE);
            }
            /*商城會員價*/
            if (goodsListBeanList.get(goodIndex).getShop_mem_status().equals("1")) {
                linearMallMember.setVisibility(View.VISIBLE);
                priceQueryMallMember.setHint(df.format(goodsListBeanList.get(goodIndex).getShop_mem_price()));
            } else {
                linearMallMember.setVisibility(View.GONE);
            }
            /*PLUS價*/
            if (goodsListBeanList.get(goodIndex).getPlus_mem_status().equals("1")) {
                linearPlus.setVisibility(View.VISIBLE);
                priceQueryPlus.setHint(df.format(goodsListBeanList.get(goodIndex).getPlus_price()));
            } else {
                linearPlus.setVisibility(View.GONE);
            }
            linearChangePrice.setVisibility(View.VISIBLE);
        });
    }

    private void setClassifyListener() {
        priceQueryEdit.setImeOptions(EditorInfo.IME_ACTION_SEND);
        /**搜索商品*/
        priceQueryEdit.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                //當actionId == XX_SEND 或者 XX_DONE時都觸發
                //或者event.getKeyCode == ENTER 且 event.getAction == ACTION_DOWN時也觸發
                //注意，這是一定要判斷event != null。因爲在某些輸入法上會返回null。
                if ((event != null && KeyEvent.KEYCODE_ENTER == event.getKeyCode() && KeyEvent.ACTION_DOWN == event.getAction())) {
                    page = 1;
                    goodsListBeanList.clear();
                    setGoodsPriceAdapter();
                    searchGoodsV1();
                }
                return false;
            }
        });
        priceQueryPopupInventory.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
                if (charSequence.toString().contains(".")) {
                    if (-1 != charSequence.toString().indexOf(".", charSequence.toString().indexOf(".") + 1)) {
                        priceQueryPopupInventory.setText(charSequence.toString().
                                substring(0, charSequence.toString().length() - 1));
                        priceQueryPopupInventory.setSelection(charSequence.length() - 1);
                    } else {
                        if (charSequence.length() - 1 - charSequence.toString().indexOf(".") > 2) {
                            charSequence = charSequence.toString().subSequence(0, charSequence.toString().indexOf(".") + 3);
                            priceQueryPopupInventory.setText(charSequence);
                            priceQueryPopupInventory.setSelection(charSequence.length());
                        }
                    }
                }
                if (charSequence.toString().trim().substring(0).equals(".")) {
                    charSequence = "0" + charSequence;
                    priceQueryPopupInventory.setText(charSequence);
                    priceQueryPopupInventory.setSelection(2);
                }

                if (charSequence.toString().startsWith("0") && charSequence.toString().trim().length() > 1) {
                    if (!charSequence.toString().substring(1, 2).equals(".")) {
                        priceQueryPopupInventory.setText(charSequence.subSequence(1, 2));
                        priceQueryPopupInventory.setSelection(1);
                        return;
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                priceQueryEdit.setText("");
                oneIndex = position;
                if (allList.get(position).getHaschild() == 1) {
                    spinner2.setVisibility(View.VISIBLE);
                    allTwoList.clear();
                    allTwoList.add(new ClassifyInfo.GoodscateBean.ChildBeanX("", "全部"));
                    for (ClassifyInfo.GoodscateBean.ChildBeanX childBeanX : allList.get(oneIndex).getChild()) {
                        allTwoList.add(childBeanX);
                    }
                    childTwoList.clear();
                    for (int i = 0; i < allTwoList.size(); i++) {
                        childTwoList.add(allTwoList.get(i).getClass_name());
                    }
                    if (childTwoList.size() == 0) {
//                        twoIndex = 9999;
                    }
                    setTwoAdapter();
//                    threeIndex = 9999;
                    childThreeList.clear();
                    setThreeAdapter();
                    spinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                        @Override
                        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                            priceQueryEdit.setText("");
                            twoIndex = position;
                            if (allTwoList.get(position).getHaschild() == 1) {
                                spinner3.setVisibility(View.VISIBLE);
                                allThreeList.clear();
                                allThreeList.add(new ClassifyInfo.GoodscateBean.ChildBeanX.ChildBean("", "全部"));
                                for (ClassifyInfo.GoodscateBean.ChildBeanX.ChildBean childBean : allTwoList.get(position).getChild()) {
                                    allThreeList.add(childBean);
                                }
                                childThreeList.clear();
                                for (int i = 0; i < allThreeList.size(); i++) {
                                    childThreeList.add(allThreeList.get(i).getClass_name());
                                }
                                if (childThreeList.size() == 0) {
//                                    threeIndex = 9999;
                                }
                                setThreeAdapter();

                                spinner3.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                                    @Override
                                    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                                        priceQueryEdit.setText("");
                                        threeIndex = position;

                                        page = 1;
                                        goodsListBeanList.clear();
                                        setGoodsPriceAdapter();
                                        searchGoodsV1();
                                    }

                                    @Override
                                    public void onNothingSelected(AdapterView<?> parent) {

                                    }
                                });
                            } else {
                                spinner3.setVisibility(View.INVISIBLE);
                            }
                            page = 1;
                            goodsListBeanList.clear();
                            setGoodsPriceAdapter();
                            searchGoodsV1();
                        }

                        @Override
                        public void onNothingSelected(AdapterView<?> parent) {

                        }
                    });
                } else {
                    spinner2.setVisibility(View.INVISIBLE);
                    spinner3.setVisibility(View.INVISIBLE);
                }
                page = 1;
                goodsListBeanList.clear();
                setGoodsPriceAdapter();
                searchGoodsV1();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

    }

    private void setOneAdapter() {
        ArrayAdapter<String> oneAdapter = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_dropdown_item, childOneList);
        //自定義下拉的字體樣式
        oneAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner1.setAdapter(oneAdapter);
    }

    private void getClassify() {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("storeid", aCache.getAsString("storeid"));
            jsonObject.put("store_id", aCache.getAsString("storeid"));
            jsonObject.put("merchant_id", aCache.getAsString("merchantid"));
            jsonObject.put("merchantid", aCache.getAsString("merchantid"));
//            jsonObject.put("operator_identity_id", aCache.getAsString("uid"));
            if ("3".equals(aCache.getAsString("userType"))) {
                jsonObject.put("operator_id", aCache.getAsString("uid"));
            }else{
                jsonObject.put("operator_id",aCache.getAsString("operator_id"));
            }
            jsonObject.put("user_type", aCache.getAsString("userType"));
        } catch (JSONException e) {
            e.printStackTrace();
        }
            HttpUtils.post(context, Common.ADD_CLASSIFICATION, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    Log.e(TAG, "onSuccess: get_classify " + text);
                    Message message = new Message();
                    Gson gson = new Gson();
                    classifyInfo = gson.fromJson(text, ClassifyInfo.class);
                    if (classifyInfo.getStatus() == 1) {
                        message.what = 1;
                    } else {
                        message.what = 2;
                    }
                    handler.sendMessage(message);
                }

                @Override
                protected void onFailure(ResponseException e) {

                }
            });
    }

    private void setTwoAdapter() {
        ArrayAdapter<String> twoAdapter = new ArrayAdapter<String>(context,
                android.R.layout.simple_spinner_dropdown_item, childTwoList);
        //自定義下拉的字體樣式
        twoAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner2.setAdapter(twoAdapter);
    }

    private void setThreeAdapter() {
        ArrayAdapter<String> threeAdapter = new ArrayAdapter<String>(context,
                android.R.layout.simple_spinner_dropdown_item, childThreeList);
        //自定義下拉的字體樣式
        threeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner3.setAdapter(threeAdapter);
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1: //獲取分類信息成功
                    allList.clear();
                    childOneList.clear();
                    childTwoList.clear();
                    childThreeList.clear();
//                    oneIndex = 0;
//                    twoIndex = 9999;
//                    threeIndex = 9999;
                    allList.add(new ClassifyInfo.GoodscateBean("", "全部"));
                    for (ClassifyInfo.GoodscateBean goodscateBean : classifyInfo.getGoodscate()) {
                        allList.add(goodscateBean);
                    }
                    Log.e(TAG, "handleMessage: list=" + allList.size() );
                    for (int i = 0; i < allList.size(); i++) {
                        childOneList.add(allList.get(i).getClass_name());
//                        if (allList.get(i).getHaschild() == 1) {
//                            allList.get(i).getChild().clear();
//                            allList.get(i).getChild().add(new ClassifyInfo.GoodscateBean.ChildBeanX("", "全部"));
//                            for (ClassifyInfo.GoodscateBean.ChildBeanX childBeanX : allList.get(i).getChild()) {
//                                allList.get(i).getChild().add(childBeanX);
//                                childTwoList.add(childBeanX.getClass_name());
//                            }
//                            for (int j = 0; j < allList.get(i).getChild().size(); j++) {
//                                if (allList.get(i).getChild().get(j).getHaschild() == 1) {
//                                    allList.get(i).getChild().get(j).getChild().clear();
//                                    allList.get(i).getChild().get(j).getChild().add(new ClassifyInfo.GoodscateBean.ChildBeanX.ChildBean("", "全部"));
//                                    Log.e(TAG, "handleMessage: i+j=" + classifyInfo.getGoodscate().size() + "=" + allList.get(i).getChild().size() );
//                                    for (ClassifyInfo.GoodscateBean.ChildBeanX.ChildBean childBean : allList.get(i).getChild().get(j).getChild()) {
//                                        allList.get(i).getChild().get(j).getChild().add(childBean);
//                                        childThreeList.add(childBean.getClass_name());
//                                    }
//                                }
//                            }
//                        }
                    }
//                    for (int i = 0; i < classifyInfo.getGoodscate().size(); i++) {
//                        allList.add(classifyInfo.getGoodscate().get(i));
//                        childOneList.add(classifyInfo.getGoodscate().get(i).getClass_name());
//                    }
//
//                    if (allList.size() > 0) {
//                        if (allList.get(0).getChild().size() > 0) {
//                            childTwoList.add("未選擇");
//                            for (int i = 0; i < allList.get(0).getChild().size(); i++) {
//                                childTwoList.add(allList.get(0).getChild().get(i).getClass_name());
//                            }
//                        }
//                    }
//
//                    if (allList.size() > 0) {
//                        if (allList.get(0).getChild().size() > 0) {
//                            if (allList.get(0).getChild().get(0).getChild().size() > 0) {
//                                childThreeList.add("未選擇");
//                                for (int i = 0; i < allList.get(0).getChild().get(0).getChild().size(); i++) {
//                                    childThreeList.add(allList.get(0).getChild().get(0).getChild().get(i).getClass_name());
//                                }
//                            }
//                        }
//                    }
                    setOneAdapter();
                    setTwoAdapter();
                    setThreeAdapter();
                    if (allList.size() > 0) {
                        page = 1;
                        goodsListBeanList.clear();
                        setGoodsPriceAdapter();
                        searchGoodsV1();
                    }
                    //Log.e(TAG, "handleMessage: size1+size2+size3--" + childOneList.size() + "+" + childTwoList.size() + "+" + childThreeList.size());
                    break;
                case 2: //獲取分類信息失敗
                    Toast.makeText(context, classifyInfo.getMsg(), Toast.LENGTH_SHORT).show();
                    break;
                case 3:
                    loadingDialog.dismiss();
                    priceQueryList.onRefreshComplete();
                    int size = priceQueryBean.getGoodslist().size();
                    if (size > 0) {
                        page++;
                        for (int i = 0; i < size; i++) {
                            goodsList.add(priceQueryBean.getGoodslist().get(i));
                        }
                    }
                    setPriceQueryAdapter();
                    break;
                case 4:
                    loadingDialog.dismiss();
                    priceQueryList.onRefreshComplete();
                    if (page != 1) {
                        Toast.makeText(context, "沒有更多數據了", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(context, priceQueryBean.getMsg(), Toast.LENGTH_SHORT).show();
                    }
                    setPriceQueryAdapter();
                    break;
                case 5:
                    loadingDialog.dismiss();
                    priceQueryList.onRefreshComplete();
                    goodsListBeanList.clear();
                    page ++;
                    for (GoodsPriceInfo.GoodsListBean goodsListBean : goodsPriceInfo.getGoodsList()) {
                        goodsListBeanList.add(goodsListBean);
                    }
                    setGoodsPriceAdapter();
                    break;
                case 6:
                    loadingDialog.dismiss();
                    priceQueryList.onRefreshComplete();
                    if (page != 1) {
                        Toast.makeText(context, "沒有更多數據了", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(context, goodsPriceInfo.getMsg(), Toast.LENGTH_SHORT).show();
                    }
                    setGoodsPriceAdapter();
                    break;
            }
        }
    };

    @OnClick({R.id.price_query_code, R.id.title_back, R.id.price_query_search, R.id.price_query_popup_cancel,
            R.id.price_query_popup_sure, R.id.price_query_popup_linear,
            R.id.linear_change_price, R.id.btn_to_top,R.id.change_price_cancel, R.id.change_price_sure})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_back:
                finish();
                break;
            case R.id.price_query_search:
                page = 1;
                goodsListBeanList.clear();
                setGoodsPriceAdapter();
                searchGoodsV1();
                break;
            case R.id.price_query_popup_cancel:
                priceQueryPopupInventory.setText("");
                priceQueryPopupLinear.setVisibility(View.GONE);
                break;
            case R.id.price_query_popup_sure:
                if ("2".equals(goodsList.get(goodIndex).getAttribute_state()) && goodsList.get(goodIndex).getSkujson().size() > 0) {
                    if ("0".equals(sku_id)) {
                        Toast.makeText(context, "請重新選擇規格", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (TextUtils.isEmpty(priceQueryPopupInventory.getText().toString())) {
                        Toast.makeText(context, "請輸入新價格", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (Double.parseDouble(priceQueryPopupInventory.getText().toString()) == 0) {
                        Toast.makeText(context, "商品新價格必須大於0", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    changePrice();
                } else {
                    if (TextUtils.isEmpty(priceQueryPopupInventory.getText().toString())) {
                        Toast.makeText(context, "請輸入新價格", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (Double.parseDouble(priceQueryPopupInventory.getText().toString()) == 0) {
                        Toast.makeText(context, "商品新價格必須大於0", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    changePrice();
                }
                break;
            case R.id.price_query_popup_linear:
                break;
            case R.id.price_query_code:
                startQrCode();
                break;
                /*改價*/
            case R.id.linear_change_price:
                break;
            case R.id.change_price_cancel:
                linearChangePrice.setVisibility(View.GONE);
                break;
            case R.id.change_price_sure:
                updatePrice();
                break;
            case R.id.btn_to_top:
                priceQueryList.getRefreshableView().setSelection(0);
                break;
        }
    }

    private void searchGoods() {
        loadingDialog.show();
        String search = priceQueryEdit.getText().toString().trim();
        JSONObject json = new JSONObject();
        try {
            json.put("storeid", aCache.getAsString("storeid"));
            json.put("merchantid", aCache.getAsString("merchantid"));
            json.put("keyword", search);
            if (TextUtils.isEmpty(search)) {
                if (allList.get(oneIndex).getChild().size() > 0 && twoIndex == 9999 && threeIndex == 9999) {
                    json.put("goodscateid", "0");
                } else {
                    if (twoIndex == 9999) {
                        json.put("goodscateid", allList.get(oneIndex).getId());
                    } else {
                        if (threeIndex == 9999) {
                            json.put("goodscateid", allList.get(oneIndex).getChild().get(twoIndex).getId());
                        } else {
                            json.put("goodscateid", allList.get(oneIndex).getChild().get(twoIndex).getChild().get(threeIndex).getId());
                        }
                    }
                }
            } else {
                json.put("goodscateid", 0);
            }
            json.put("page", page);
            json.put("limit", page_limit);
            HttpUtils.post(context, Common.SEARCH_GOODS, json, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
//                    Log.e(TAG, "onSuccess: serarch_goods" + text);
                    priceQueryBean = GsonUtils.JsonToBean(text, PriceQueryBean.class);
                    Message msg = new Message();
                    if (priceQueryBean.getStatus() == 1) {
                        msg.what = 3;
                    } else {
                        msg.what = 4;
                    }
                    handler.handleMessage(msg);
                }

                @Override
                protected void onFailure(ResponseException e) {
                    loadingDialog.dismiss();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /*查詢商品*/
    private void searchGoodsV1() {
        loadingDialog.show();
        String search = priceQueryEdit.getText().toString().trim();
        JSONObject json = new JSONObject();
        try {
            json.put("storeid", aCache.getAsString("storeid"));
            json.put("merchantid", aCache.getAsString("merchantid"));
            json.put("keyword", search);
            if (allList.size() > 0) {
                if (allTwoList.size() > 0 && allList.get(oneIndex).getHaschild() == 1) {
                    if (allThreeList.size() > 0 && allTwoList.get(twoIndex).getHaschild() == 1) {
                        json.put("person1", allList.get(oneIndex).getId());
                        json.put("person2", allTwoList.get(twoIndex).getId());
                        json.put("person3", allThreeList.get(threeIndex).getId());
                    } else {
                        json.put("person1", allList.get(oneIndex).getId());
                        json.put("person2", allTwoList.get(twoIndex).getId());
                        json.put("person3", "");
                    }
                } else {
                    json.put("person1", allList.get(oneIndex).getId());
                    json.put("person2", "");
                    json.put("person3", "");
                }
            } else {
                json.put("person1", "");
                json.put("person2", "");
                json.put("person3", "");
            }
            json.put("page", page);
            json.put("limit", page_limit);
            HttpUtils.post(context, Common.SEARCH_GOODS_V1, json, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
//                    Log.e(TAG, "onSuccess: serarch_goods" + text);
                    Gson gson = new Gson();
                    goodsPriceInfo = gson.fromJson(text, GoodsPriceInfo.class);
//                    goodsPriceInfo = GsonUtils.JsonToBean(text, GoodsPriceInfo.class);
                    Message msg = new Message();
                    if (goodsPriceInfo.getStatus() == 1) {
                        msg.what = 5;
                    } else {
                        msg.what = 6;
                    }
                    handler.handleMessage(msg);
                }

                @Override
                protected void onFailure(ResponseException e) {
                    loadingDialog.dismiss();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void changePrice() {
        loadingDialog.show();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("storeid", aCache.getAsString("storeid"));
            jsonObject.put("merchantid", aCache.getAsString("merchantid"));
            jsonObject.put("goodsInfo", new Gson().toJson(goodsList.get(goodIndex)));
            jsonObject.put("newprice", priceQueryPopupInventory.getText().toString());
            jsonObject.put("id", goodsList.get(goodIndex).getId());
            jsonObject.put("skuid", sku_id);
            jsonObject.put("operator_id", aCache.getAsString("uid"));
            jsonObject.put("user_type", aCache.getAsString("userType"));
            HttpUtils.post(context, Common.CHANGE_GOOD_PRICE, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    loadingDialog.dismiss();
                    try {
                        JSONObject json = new JSONObject(text);
                        Toast.makeText(context, json.getString("msg"), Toast.LENGTH_SHORT).show();
                        if (json.getInt("status") == 1) {
                            priceQueryPopupInventory.setText("");
                            priceQueryPopupLinear.setVisibility(View.GONE);
                            sku_id = "0";
                            page = 1;
                            goodsList.clear();
                            searchGoods();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                protected void onFailure(ResponseException e) {

                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void updatePrice() {
        loadingDialog.show();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("storeid", aCache.getAsString("storeid"));
            jsonObject.put("merchantid", aCache.getAsString("merchantid"));
//            JSONObject object = new JSONObject();
//            object.put("attribute_state", goodsListBeanList.get(goodIndex).getAttribute_state());
//            object.put("cost_price", goodsListBeanList.get(goodIndex).getCost_price());
//            object.put("goods_class_id", goodsListBeanList.get(goodIndex).getGoods_class_id());
//            object.put("goods_code", goodsListBeanList.get(goodIndex).getGoods_code());
//            object.put("goods_id", goodsListBeanList.get(goodIndex).getGoods_id());
//            object.put("goods_name", goodsListBeanList.get(goodIndex).getGoods_name());
//            object.put("goods_num", goodsListBeanList.get(goodIndex).getGoods_num());
//            object.put("goods_number", goodsListBeanList.get(goodIndex).getGoods_number());
//            object.put("online_price", goodsListBeanList.get(goodIndex).getOnline_price());
//            object.put("online_state", goodsListBeanList.get(goodIndex).getOnline_state());
//            object.put("plus_mem_status", goodsListBeanList.get(goodIndex).getPlus_mem_status());
//            object.put("plus_price", goodsListBeanList.get(goodIndex).getPlus_price());
//            object.put("retail_price", goodsListBeanList.get(goodIndex).getRetail_price());
//            object.put("shop_mem_price", goodsListBeanList.get(goodIndex).getShop_mem_price());
//            object.put("shop_mem_status", goodsListBeanList.get(goodIndex).getShop_mem_status());
//            object.put("sku_code", goodsListBeanList.get(goodIndex).getSku_code());
//            object.put("sku_goods_number", goodsListBeanList.get(goodIndex).getSku_goods_number());
//            object.put("sku_id", goodsListBeanList.get(goodIndex).getSku_id());
//            object.put("sku_name", goodsListBeanList.get(goodIndex).getSku_name());
//            object.put("store_mem_price", goodsListBeanList.get(goodIndex).getStore_mem_price());
//            object.put("store_mem_status", goodsListBeanList.get(goodIndex).getStore_mem_status());
//            jsonObject.put("goodsInfo", object);
            jsonObject.put("goodsInfo", new Gson().toJson(goodsListBeanList.get(goodIndex)));
            jsonObject.put("new_retail_price", priceQueryStoreRetail.getText().toString());
            jsonObject.put("new_store_mem_price", priceQueryStoreMember.getText().toString());
            jsonObject.put("new_online_price", priceQueryMall.getText().toString());
            jsonObject.put("new_shop_mem_price", priceQueryMallMember.getText().toString());
            jsonObject.put("new_plus_price", priceQueryPlus.getText().toString());
            jsonObject.put("id", goodsListBeanList.get(goodIndex).getGoods_id());
            jsonObject.put("skuid", sku_id);
            jsonObject.put("operator_id", aCache.getAsString("uid"));
            jsonObject.put("user_type", aCache.getAsString("userType"));
            jsonObject.put("type", "Android");
            HttpUtils.post(context, Common.UPDATE_GOOD_PRICE, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    loadingDialog.dismiss();
                    try {
                        JSONObject json = new JSONObject(text);
                        Toast.makeText(context, json.getString("msg"), Toast.LENGTH_SHORT).show();
                        if (json.getInt("status") == 1) {
                            priceQueryStoreRetail.setText("");
                            priceQueryStoreMember.setText("");
                            priceQueryMall.setText("");
                            priceQueryMallMember.setText("");
                            priceQueryPlus.setText("");
                            linearChangePrice.setVisibility(View.GONE);
                            sku_id = "0";
                            page = 1;
                            goodsListBeanList.clear();
                            setGoodsPriceAdapter();
                            searchGoodsV1();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                protected void onFailure(ResponseException e) {

                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    // 開始掃碼
    private void startQrCode() {
        if (ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            // 申請權限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, Constant.REQ_PERM_CAMERA);
            return;
        }
        // 二維碼掃碼
        Intent intent = new Intent(context, CaptureActivity.class);
        startActivityForResult(intent, Constant.REQ_QR_CODE);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case Constant.REQ_PERM_CAMERA:
                // 攝像頭權限申請
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 獲得授權
                    startQrCode();
                } else {
                    // 被禁止授權
                    Toast.makeText(context, "請至權限中心打開本應用的相機訪問權限", Toast.LENGTH_LONG).show();
                }
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode != 1 && requestCode == Constant.REQ_QR_CODE && resultCode == RESULT_OK) {//掃描結果回調
            Bundle bundle = data.getExtras();
            page = 1;
            goodsList.clear();
            priceQueryEdit.setText(bundle.getString(Constant.INTENT_EXTRA_KEY_QR_SCAN));
            searchGoodsV1(); //查詢商品
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {

                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否則所有的組件都不會有TouchEvent了
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);

    }

    public boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            //獲取輸入框當前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 點擊的是輸入框區域，保留點擊EditText的事件
                return false;
            } else {
                return true;
            }
        }
        return false;
    }

}
